/**
 * 立即购买服务 - 新版本
 * 参照checkout页面的支付宝支付功能，但使用/createNow接口
 */
import http from "@/utils/http/http.js"
import { AlipayService } from "@/utils/payment/alipay.js"
import { useUserStore } from "@/store/user"
//import uni from "uni-app"

export class BuyNowService {
  constructor() {
    this.alipayService = new AlipayService()
    this.showPaymentModal = false
    this.showPaymentWebview = false
    this.currentOrderNo = ""
    this.alipayFormData = ""
    this.paymentUrl = ""
  }

  /**
   * 立即购买商品 - 新版本
   * @param {Object} product - 商品信息
   * @param {Number} quantity - 购买数量
   * @param {String} remark - 订单备注
   */
  async buyNow(product, quantity = 1, remark = "立即购买") {
    const userStore = useUserStore()

    // 检查登录状态
    if (!userStore.isLoggedIn) {
      uni.showToast({
        title: "请先登录",
        icon: "none",
      })
      throw new Error("用户未登录")
    }

    // 检查商品状态
    if (product.status === 0) {
      uni.showToast({
        title: "该商品已下架",
        icon: "none",
      })
      throw new Error("商品已下架")
    }

    if (product.totalStock <= 0) {
      uni.showToast({
        title: "该商品库存不足",
        icon: "none",
      })
      throw new Error("库存不足")
    }

    if (quantity > product.totalStock) {
      uni.showToast({
        title: "购买数量超过库存",
        icon: "none",
      })
      throw new Error("购买数量超过库存")
    }

    try {
      // 显示加载中
      uni.showLoading({
        title: "处理中...",
        mask: true,
      })

      // 构建立即购买订单数据 - 不需要地址
      const orderData = {
        productId: product.id,
        quantity: quantity,
        remark: remark,
      }

      console.log("立即购买订单数据:", JSON.stringify(orderData))

      // 调用立即购买接口
      const response = await http.post("/api/orders/createNow", orderData, {
        header: {
          Authorization: `Bearer ${userStore.token}`,
        },
      })

      if (response.code === 200) {
        const orderNo = response.data
        console.log("立即购买订单创建成功:", orderNo)
        this.currentOrderNo = orderNo

        // 发起支付宝支付
        await this.initiateAlipayPayment(orderNo)

        uni.hideLoading()
        return {
          success: true,
          orderNo: orderNo,
        }
      } else {
        uni.hideLoading()
        uni.showToast({
          title: response.message || "创建订单失败",
          icon: "none",
        })
        throw new Error(response.message || "创建订单失败")
      }
    } catch (error) {
      uni.hideLoading()
      console.error("立即购买失败:", error)
      throw error
    }
  }

  /**
   * 发起支付宝支付 - 参照checkout页面
   * @param {String} orderNo - 订单号
   */
  async initiateAlipayPayment(orderNo) {
    const userStore = useUserStore()

    try {
      const paymentData = {
        orderNo: orderNo,
        paymentType: 2, // 支付宝支付
      }

      console.log("发起支付宝支付:", paymentData)

      const response = await http.post("/api/orders/pay", paymentData, {
        header: {
          Authorization: `Bearer ${userStore.token}`,
        },
      })

      if (response.code === 200 && response.data && response.data.payUrl) {
        // 保存支付表单数据
        this.alipayFormData = response.data.payUrl

        // 直接打开支付宝支付
        await this.openAlipayPayment()

        console.log("支付宝支付请求成功")
      } else {
        throw new Error(response.message || "发起支付失败")
      }
    } catch (error) {
      console.error("发起支付失败:", error)
      throw error
    }
  }

  /**
   * 打开支付宝支付页面 - 参照checkout页面
   */
  async openAlipayPayment() {
    try {
      if (!this.alipayFormData) {
        uni.showToast({
          title: "支付数据异常",
          icon: "none",
        })
        return
      }

      // #ifdef MP-WEIXIN
      // 微信小程序中，复制支付链接
      uni.setClipboardData({
        data: this.alipayFormData,
        success: () => {
          uni.showModal({
            title: "支付提示",
            content: "支付链接已复制，请在浏览器中打开完成支付",
            showCancel: false,
            confirmText: "知道了",
          })
        },
      })
      // #endif

      // #ifdef H5
      // H5环境中，直接打开新窗口
      const payWindow = window.open("", "_blank", "width=800,height=600,scrollbars=yes,resizable=yes")
      if (payWindow) {
        const paymentHtml = this.createPaymentHtml()
        payWindow.document.write(paymentHtml)
        payWindow.document.close()
      }
      // #endif

      // #ifdef APP-PLUS
      // App环境中的多种处理方式
      await this.handleAppAlipayPayment()
      // #endif

      // 跳转到支付结果页面
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/orders/success?orderNo=${this.currentOrderNo}`,
        })
      }, 2000)
    } catch (error) {
      console.error("打开支付宝支付页面失败:", error)
      uni.showToast({
        title: "打开支付页面失败",
        icon: "none",
      })
    }
  }

  /**
   * App环境中的支付宝支付处理
   */
  async handleAppAlipayPayment() {
    try {
      console.log("使用浏览器支付方案")

      // 直接使用浏览器支付
      const result = await this.alipayService.pay(this.alipayFormData)
      this.handlePaymentResult(result)
    } catch (error) {
      console.error("浏览器支付失败:", error)

      // 显示用户友好的错误信息
      uni.showModal({
        title: "支付提示",
        content: "无法打开支付页面，请检查设备是否安装浏览器应用",
        showCancel: true,
        cancelText: "取消",
        confirmText: "重试",
        success: (res) => {
          if (res.confirm) {
            // 重试支付
            this.handleAppAlipayPayment()
          } else {
            // 取消支付
            this.cancelPayment()
          }
        },
      })
    }
  }

  /**
   * 创建支付页面HTML - 参照checkout页面
   */
  createPaymentHtml() {
    return `
      <!DOCTYPE html>
      <html>
      <head>
        <title>支付宝支付</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body { 
            font-family: -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #1677ff 0%, #40a9ff 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
          }
          .container {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            text-align: center;
            max-width: 400px;
            width: 100%;
          }
          .logo {
            width: 80px;
            height: 80px;
            background: #1677ff;
            border-radius: 50%;
            margin: 0 auto 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
            font-weight: bold;
          }
          .title {
            font-size: 24px;
            color: #333;
            margin-bottom: 10px;
          }
          .subtitle {
            color: #666;
            margin-bottom: 30px;
          }
          .btn {
            width: 100%;
            height: 50px;
            background: #1677ff;
            color: white;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 15px;
          }
          .btn:hover {
            background: #0958d9;
            transform: translateY(-2px);
          }
          .cancel-btn {
            background: #f5f5f5;
            color: #666;
          }
          .form-container {
            display: none;
          }
          .loading {
            display: none;
            margin: 20px 0;
          }
          .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #1677ff;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
          }
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="logo">支</div>
          <h2 class="title">支付宝支付</h2>
          <p class="subtitle">安全便捷的支付体验</p>
          
          <div id="payment-content">
            <div class="status">订单号: ${this.currentOrderNo}</div>
            <button class="btn" onclick="startPayment()">确认支付</button>
            <button class="btn cancel-btn" onclick="cancelPayment()">取消支付</button>
          </div>
          
          <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>正在跳转到支付宝...</p>
          </div>
          
          <div class="form-container">
            ${this.alipayFormData}
          </div>
        </div>
        
        <script>
          function startPayment() {
            document.getElementById('payment-content').style.display = 'none';
            document.getElementById('loading').style.display = 'block';
            
            setTimeout(() => {
              const form = document.querySelector('form');
              if (form) {
                form.submit();
              } else {
                alert('支付数据异常，请重试');
                resetPayment();
              }
            }, 1500);
          }
          
          function cancelPayment() {
            if (confirm('确定要取消支付吗？')) {
              try {
                if (window.plus && plus.webview) {
                  plus.webview.currentWebview().close();
                } else if (window.parent) {
                  window.parent.postMessage({ action: 'cancel' }, '*');
                }
              } catch (e) {
                console.log('关闭支付页面失败:', e);
              }
            }
          }
          
          function resetPayment() {
            document.getElementById('payment-content').style.display = 'block';
            document.getElementById('loading').style.display = 'none';
          }
          
          window.onload = function() {
            console.log('支付页面加载完成');
          };
        </script>
      </body>
      </html>
    `
  }

  /**
   * 处理支付结果 - 参照checkout页面
   */
  handlePaymentResult(result) {
    console.log("支付结果:", result)

    if (result.resultStatus === "9000") {
      // 支付成功
      uni.showToast({
        title: "支付成功",
        icon: "success",
      })

      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/orders/success?orderNo=${this.currentOrderNo}`,
        })
      }, 1500)
    } else if (result.resultStatus === "6001") {
      // 用户取消支付
      uni.showToast({
        title: "支付已取消",
        icon: "none",
      })
    } else {
      // 支付失败
      uni.showToast({
        title: "支付失败",
        icon: "none",
      })
    }
  }

  /**
   * 取消支付
   */
  cancelPayment() {
    uni.showToast({
      title: "支付已取消",
      icon: "none",
    })
  }

  /**
   * 检查支付状态 - 参照checkout页面
   */
  async checkPaymentStatus() {
    const userStore = useUserStore()

    try {
      const response = await http.get(`/api/orders/payment-status/${this.currentOrderNo}`, {
        header: {
          Authorization: `Bearer ${userStore.token}`,
        },
      })

      if (response.code === 200) {
        const paymentStatus = response.data.status

        if (paymentStatus === "SUCCESS") {
          uni.showToast({
            title: "支付成功",
            icon: "success",
          })

          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/orders/success?orderNo=${this.currentOrderNo}`,
            })
          }, 1500)
        } else if (paymentStatus === "FAILED") {
          uni.showToast({
            title: "支付失败",
            icon: "none",
          })
        } else {
          uni.showToast({
            title: "支付状态确认中...",
            icon: "none",
          })
        }
      }
    } catch (error) {
      console.error("检查支付状态失败:", error)
      uni.showToast({
        title: "检查支付状态失败",
        icon: "none",
      })
    }
  }
}

// 导出单例
export const buyNowService = new BuyNowService()
